const Koa = require('koa') // 引入koa
const Router = require('koa-router') // 引入koa-router
const serve = require('koa-static')
const path = require('path')
const cors = require('koa2-cors')
const koaBody = require('koa-body')
const multer = require('@koa/multer')
const matter = require('gray-matter')
const fs = require('fs')
const { marked } = require('marked')
const data = fs.readFileSync('./test.md', 'utf-8')

const app = new Koa() // 创建koa应用
const router = new Router() // 创建路由，支持传递参数
let imgUrl = ''
const imgUrlList = []
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './upload')
    },
    filename: function (req, file, cb) {
        const fileFormat = (file.originalname).split('.')
        const url = Date.now() + '.' + fileFormat[fileFormat.length - 1]
        if (file.fieldname === 'avatar') {
            imgUrlList.push(`http://localhost:3000/${url}`)
        } else {
            imgUrl = url
        }
        cb(null, url)
    }
})
const upload = multer({ storage })
router.get('/', async (ctx) => {
    ctx.type = 'html'
    ctx.body = '<h1>hello world!</h1>'
})

router.post(
    '/upload-multiple-files',
    upload.fields([
        {
            name: 'avatar',
            maxCount: 3
        },
        {
            name: 'boop',
            maxCount: 2
        }
    ]),
    ctx => {
        console.log('ctx.request.files', ctx.request.files)
        ctx.body = {
            url: imgUrlList
        }
    }
)

router.post('/upload', upload.single('file'), async (ctx) => {
    console.log('ctx.request.body', ctx.file)
    ctx.body = {
        url: `http://localhost:3000/${imgUrl}`
    }
})

router.post('/mdtohtml', async (ctx) => {
    const requestBody = ctx.request.body
    console.log(requestBody)
    const { content, data: forntMatter } = matter(requestBody.text)
    const html = marked.parse(content)
    console.log(forntMatter, 'html')
    ctx.body = {
        html, forntMatter
    }
})

app.use(cors())
    .use(koaBody())
    .use(router.routes())
    .use(router.allowedMethods())
    .use(
        serve(path.join(__dirname, './upload'))
    )

// 启动服务监听本地3000端口
app.listen(3003, () => {
    console.log('应用已经启动，http://localhost:3003')
})
